package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured
import sun.misc.BASE64Encoder

import java.security.MessageDigest
import java.text.SimpleDateFormat

class RemoteSignFaceController
{
    def springSecurityService
    def questionnaireInstanceService
    def componentService
    //视频面签web页登录
    @Secured('permitAll')
    def login()
    {
    }

    @Secured(['isAuthenticated()'])
    //视频面签web页
    def remoteSignface()
    {

    }

    @Secured(['isAuthenticated()'])
    //web用户获取token
    def getYunxinTokenByUser()
    {

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def result = []
        if (user?.yxToken)
        {
            result = [code: 200, info: [token: user?.yxToken, accid: user?.cellphone, name: user?.username, linkAccid: "17610867397"]] as JSON
        }
        else
        {
            def url = new java.net.URL("https://api.netease.im/nimserver/user/create.action")
            def requestData
            def appKey = "b11092a625ee18f79f18479eac4ad862"
            def nonce = "12345678"
            def appSecret = "5f4b3836bded"
            def curTime = (new Date().time / 1000).intValue().toString()
            def checkSum = getCheckSum(appSecret, nonce, curTime)
            requestData = "accid=${user?.cellphone}&name=${user?.username}"
            try
            {
                def connection = (java.net.HttpURLConnection) url.openConnection()
                connection.setDoOutput(true)
                connection.setRequestMethod("POST")
                connection.setRequestProperty("AppKey", appKey)
                connection.setRequestProperty("Nonce", nonce)
                connection.setRequestProperty("CurTime", curTime)
                connection.setRequestProperty("CheckSum", checkSum)
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
                connection.setConnectTimeout(10000)
                def r = connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text }
                result = grails.converters.JSON.parse(r)
                println(result)
                if (result.code == 200)
                {
                    user.yxToken = result.info.token
                    user.save flush: true
                }
                else
                {
                    println("请求token失败")
                    result = refreshToken(user)

                }
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace()
                println(e)
            }
        }
        render(result)
        return null
    }

    def refreshToken(User user)
    {
        def result
        def url = new java.net.URL("https://api.netease.im/nimserver/user/refreshToken.action")
        def requestData
        def appKey = "b11092a625ee18f79f18479eac4ad862"
        def nonce = "12345678"
        def appSecret = "5f4b3836bded"
        def curTime = (new Date().time / 1000).intValue().toString()
        def checkSum = getCheckSum(appSecret, nonce, curTime)
        requestData = "accid=${user?.cellphone}&name=${user?.fullName}"
        try
        {
            def connection = (java.net.HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setRequestProperty("AppKey", appKey)
            connection.setRequestProperty("Nonce", nonce)
            connection.setRequestProperty("CurTime", curTime)
            connection.setRequestProperty("CheckSum", checkSum)
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
            connection.setConnectTimeout(10000)
            def r = connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text }
            result = grails.converters.JSON.parse(r)
            println(result)
            if (result.code == 200)
            {
                opportunity.yxToken = result.info.token
                opportunity.save flush: true
            }
            else
            {
                println("请求token失败")
            }
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace()
            println(e)
        }
        return result
    }

    @Secured('permitAll')
    def subscribe()
    {
        def result
        def url = new java.net.URL("https://api.netease.im/nimserver/event/subscribe/add.action")
        def requestData
        def appKey = "b11092a625ee18f79f18479eac4ad862"
        def nonce = "12345678"
        def appSecret = "5f4b3836bded"
        def curTime = (new Date().time / 1000).intValue().toString()
        def checkSum = getCheckSum(appSecret, nonce, curTime)
        def publisherAccids = ['17610867397', '18310333320'].toString()
        requestData = "accid=18012345678&eventType=1&ttl=2592000&publisherAccids=${publisherAccids}"
        try
        {
            def connection = (java.net.HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setRequestProperty("AppKey", appKey)
            connection.setRequestProperty("Nonce", nonce)
            connection.setRequestProperty("CurTime", curTime)
            connection.setRequestProperty("CheckSum", checkSum)
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
            connection.setConnectTimeout(10000)
            def r = connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text }
            result = grails.converters.JSON.parse(r)
            println(result)
            if (result.code == 200)
            {

            }
            else
            {
                println("请求token失败")
            }
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace()
            println(e)
        }
        render(result)
        return null
    }

    @Secured('permitAll')
    def querySubscribe()
    {
        def result
        def url = new java.net.URL("https://api.netease.im/nimserver/event/subscribe/query.action")
        def requestData
        def appKey = "b11092a625ee18f79f18479eac4ad862"
        def nonce = "12345678"
        def appSecret = "5f4b3836bded"
        def curTime = (new Date().time / 1000).intValue().toString()
        def checkSum = getCheckSum(appSecret, nonce, curTime)
        def publisherAccids = ['17610867397']
        requestData = "accid=18012345678&eventType=1&publisherAccids=${publisherAccids}"
        try
        {
            def connection = (java.net.HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setRequestProperty("AppKey", appKey)
            connection.setRequestProperty("Nonce", nonce)
            connection.setRequestProperty("CurTime", curTime)
            connection.setRequestProperty("CheckSum", checkSum)
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
            connection.setConnectTimeout(10000)
            def r = connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text }
            result = grails.converters.JSON.parse(r)
            println(result)
            if (result.code == 200)
            {

            }
            else
            {
                println("请求token失败")
            }
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace()
            println(e)
        }
        render(result)
        return null
    }

    private static final char[] HEX_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']

    def encode(String algorithm, String value)
    {
        if (value == null)
        {
            return null
        }
        try
        {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm)
            messageDigest.update(value.getBytes())
            return getFormattedText(messageDigest.digest())
        }
        catch (Exception e)
        {
            throw new RuntimeException(e)
        }
    }

    def getFormattedText(def bytes)
    {
        int len = bytes.length
        StringBuilder buf = new StringBuilder(len * 2)
        for (
            int j = 0;
                j < len;
                j++)
        {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f])
            buf.append(HEX_DIGITS[bytes[j] & 0x0f])
        }
        return buf.toString()
    }

    def getCheckSum(String appSecret, String nonce, String curTime)
    {
        return encode("sha1", appSecret + nonce + curTime)
    }

    def getMD5(String requestBody)
    {
        return encode("md5", requestBody)
    }

    def base()
    {
        new BASE64Encoder().encode()
    }

    //设置用户的云信状态 type(1:在线，2：占线 )
    @Secured(['isAuthenticated()'])
    @Transactional
    def setUserStatus()
    {
        def username = springSecurityService.getPrincipal().username
        def estateQueryParam = new HashMap()
        estateQueryParam['query1'] = params?.status
        estateQueryParam['query2'] = username
        User.executeUpdate("update User u set u.yxConnectedStatus=:query1 ,u.yxConnectedDate=sysdate where username =:query2", estateQueryParam)
    }

    @Secured(['isAuthenticated()'])
    def getOpportunity()
    {
        //        def opportunity = Opportunity.findBySerialNumber("5T1-3QP-F39")

        def estateQueryParam = new HashMap()
        estateQueryParam['query1'] = params?.serialNumber
        def opportunity = Opportunity.executeQuery("select new map(o.id as id,o.fullName as fullName,o.idNumber as idNumber ," + "o.cellphone as cellphone,o.loanDuration as loanDuration,o.product.name as productName ," + "o.requestedAmount as requestedAmount,o.account.name as accountName,o.account.parent.name as accountPname) " + "from Opportunity o where lower(o.serialNumber) = lower(:query1)", estateQueryParam)
        def listOfAttachments
        if (opportunity)
        {
            def estateQueryParam1 = new HashMap()
            estateQueryParam1['query1'] = opportunity?.id
            listOfAttachments = Attachments.executeQuery("select new map (a.fileUrl as fileUrl,a.type.name as typeName ,a.createdDate as createdDate )" + "from Attachments a where a.opportunity.id=:query1 and (a.type.name like '%身份证%' or a.type.name like '%面签%')", estateQueryParam1)
        }
        def username = springSecurityService.getPrincipal().username
        def op1 = Opportunity.findById(opportunity?.id)
        op1.setInterviewUser(User.findByUsername(username))
        op1.save(flush: true)
        render([opportunity: opportunity, attachments: listOfAttachments] as JSON)
    }

    @Secured(['isAuthenticated()'])
    @Transactional
    def questionnaireSurvey1(Opportunity opportunity)
    {
        //        def opportunity = Opportunity.findBySerialNumber("5T1-3QP-F39")
        //        def opportunity = Opportunity.findBySerialNumber(params?.serialNumber.toUpperCase())
        // 初始化问卷
        questionnaireInstanceService.initQuestionnaireInstance(opportunity)

        def questionnaireInstance = QuestionnaireInstance.findByTypeAndOpportunity(QuestionnaireType.findByName(opportunity?.product?.name), opportunity)
        println questionnaireInstance.toString()
        respond opportunity, model: [questionnaireInstance: questionnaireInstance]
    }

    @Secured(['isAuthenticated()'])
    @Transactional
    def questionnaireSurvey1Save(Opportunity opportunity)
    {
        opportunity.interviewMemo = params?.interviewMemo
        opportunity.interviewResult = params?.interviewResult
        opportunity.save flush: true
        def questionnaireInstanceId = params['questionnaireInstanceId']
        def questionnaireInstance = QuestionnaireInstance.findById(questionnaireInstanceId)
        questionnaireInstance?.questions?.each { question ->
            if (question?.questionType == "input")
            {
                def questionValue = params[question?.name]
                if (questionValue)
                {
                    question?.value = questionValue
                    if (question?.validate())
                    {
                        question.save flush: true
                    }
                    else
                    {
                        println question.errors
                    }
                }
            }

            if (question?.questionType == "radio")
            {
                OptionInstance.findAllByQuestionInstance(question)?.each { option ->
                    def optionName = params[question?.name]
                    if (option?.name == optionName)
                    {
                        option?.selected = true
                        if (option?.validate())
                        {
                            option.save flush: true
                        }
                        else
                        {
                            println option.errors
                        }
                    }
                }
            }

            if (question?.questionType == "checkbox")
            {
                OptionInstance.findAllByQuestionInstance(question)?.each { option ->
                    def optionValue = params[option?.name]
                    if (optionValue)
                    {
                        option?.selected = optionValue
                        if (option?.validate())
                        {
                            option.save flush: true
                        }
                        else
                        {
                            println option.errors
                        }
                    }
                }
            }
        }

        //        approveStage(opportunity)
    }

    @Secured('permitAll')
    def form1()
    {

    }

    @Secured('permitAll')
    def form2()
    {

    }

    @Secured('permitAll')
    def form3()
    {

    }

    @Secured('permitAll')
    def form4()
    {

    }

    //订单信息修改页
    @Secured('permitAll')
    def editOpportunity()
    {
        def opportunity = Opportunity.find("from Opportunity o where lower(o.serialNumber) = lower(${params?.serialNumber})")

        //问卷
        //        questionnaireInstanceService.initQuestionnaireInstance(opportunity)
        //
        //        def questionnaireInstance = QuestionnaireInstance.findByTypeAndOpportunity(QuestionnaireType.findByName(opportunity?.product?.name), opportunity)
        //todo 风险决策结果
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        //todo 预警信息

        respond opportunity, model: [opportunity: opportunity, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys]
    }

    @Secured('permitAll')
    def interviewList()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (!user)
        {
            redirect(controller: "remoteSignFace", action: "login")
            return
        }
        def offset = params?.offset
        def max = params?.max
        def fullName = params?.fullName
        def cellphone = params?.cellphone
        def idNumber = params?.idNumber
        def estateQueryParam = new HashMap()
        def sql = "select new map(o.id as id,o.serialNumber as serialNumber ,o.fullName as fullName ,interviewResult as interviewResult,o.cellphone as cellphone ,o.idNumber as idNumber,o.interviewDate as interviewDate) "
        def countSql = "select count(*) "
        estateQueryParam['query'] = user.id
        sql += "from Opportunity o where  o.interviewUser.id=:query "
        countSql += "from Opportunity o where  o.interviewUser.id=:query "

        if (fullName)
        {
            estateQueryParam['query1'] = '%' + params?.fullName + '%'
            sql += " and o.fullName like :query1"
            countSql += " and o.fullName like :query1"
        }
        if (cellphone)
        {
            estateQueryParam['query2'] = '%' + params?.cellphone + '%'
            sql += " and o.cellphone like :query2 "
            countSql += " and o.cellphone like :query2"
        }
        if (idNumber)
        {
            estateQueryParam['query3'] = '%' + params?.idNumber + '%'
            sql += " and o.idNumber like :query3"
            countSql += " and o.idNumber like :query3"
        }
        def count = Opportunity.executeQuery(countSql, estateQueryParam)
        def opportunitys = Opportunity.executeQuery(sql, estateQueryParam, [offset: offset, max: max]).asList()
        respond opportunitys, model: [opportunitys: opportunitys, count: count, params: params]
    }

    @Transactional
    @Secured('permitAll')
    def interviewMessage(Opportunity opportunity)
    {
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        questionnaireInstanceService.initQuestionnaireInstance(opportunity)
        def questionnaireInstance = QuestionnaireInstance.findByTypeAndOpportunity(QuestionnaireType.findByName(opportunity?.product?.name), opportunity)
        respond opportunity, model: [opportunity: opportunity, questionnaireInstance: questionnaireInstance, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys]
    }

    @Secured('permitAll')
    def editOpportunitySave(Opportunity opportunity)
    {
        // 保存借款人信息 并更新opportunity的借款人信息
        //        def contact =opportunity.contact
        ////        contact.birthday=new SimpleDateFormat("yyyy年MM月dd日").parse(params?.contact?.birthday)
        //        if(contact.validate()){
        //            contact.save(flush:true)
        //        }else{
        //            println contact.errors
        //        }
        //        opportunity.fullName = params?.contact?.fullName
        //        opportunity.cellphone = params?.contact?.cellphone
        //        opportunity.idNumber = params?.contact?.idNumber
        //        opportunity.maritalStatus = params?.contact?.maritalStatus
        //        //联系人信息
        //        if(params?.linkContact0?.id){
        //            def contact1 = Contact.findById(params?.linkContact0?.id)
        //            def  opportunityContact =OpportunityContact.findById(params?.linkContact0?.opportunityContact?.id)
        //            contact1.fullName=params?.linkContact0?.fullName
        //            opportunityContact.connectedType=OpportunityContactType.findById(params?.linkContact0?.connectedType)
        //            contact1.companyName=params?.linkContact0?.companyName
        //            contact1.cellphone=params?.linkContact0?.cellphone
        //            if(contact1.validate()){
        //                contact1.save(flush:true)
        //            }else{
        //                println contact1.errors
        //            }
        //            if(opportunityContact.validate()){
        //                opportunityContact.save(flush:true)
        //            }else{
        //                println opportunityContact.errors
        //            }
        //
        //        }
        //        if(params?.linkContact1?.id){
        //            def contact1 = Contact.findById(params?.linkContact1?.id)
        //            def  opportunityContact =OpportunityContact.findById(params?.linkContact1?.opportunityContact?.id)
        //            contact1.fullName=params?.linkContact1?.fullName
        //            opportunityContact.connectedType=OpportunityContactType.findById(params?.linkContact1?.connectedType)
        //            contact1.companyName=params?.linkContact1?.companyName
        //            contact1.cellphone=params?.linkContact1?.cellphone
        //            if(contact1.validate()){
        //                contact1.save(flush:true)
        //            }else{
        //                println contact1.errors
        //            }
        //            if(opportunityContact.validate()){
        //                opportunityContact.save(flush:true)
        //            }else{
        //                println opportunityContact.errors
        //            }
        //
        //        }
        //产品信息
        def numberOfAccount3 = params?.bankAccount3?.numberOfAccount
        if (numberOfAccount3)
        {
            def bankAccount3 = new BankAccount(params?.bankAccount3)
            if (bankAccount3.validate())
            {
                bankAccount3.save flush: true

                def contatBankAccount = new ContactBankAccount()
                contatBankAccount.contact = opportunity?.contact
                contatBankAccount.bankAccount = bankAccount3
                contatBankAccount.save flush: true
            }
            else
            {
                println bankAccount3.errors
            }
        }
        if (opportunity?.product?.name == '汽车分期')
        {
            def vehicle = Vehicle.findByOpportunity(opportunity)
            opportunity.ownFunds = params?.ownFunds ? params?.ownFunds.toDouble() : 0
            if (vehicle)
            {
                vehicle.vehicleBrand = params?.vehicle.vehicleBrand
                vehicle.vehicleSeries = params?.vehicle.vehicleSeries
                vehicle.manufacturer = params?.vehicle.manufacturer
                vehicle.engineCode = params?.vehicle.engineCode
                vehicle.carframeCode = params?.vehicle.carframeCode
                vehicle.manufacturerVehicleMarque = params?.vehicle.manufacturerVehicleMarque
                vehicle.vehicleAmount = params?.vehicle.vehicleAmount ? params?.vehicle.vehicleAmount.toDouble() : 0
                vehicle.distributorCustomerCode = params?.vehicle.distributorCustomerCode
                vehicle.vehicleProvider = params?.vehicle.vehicleProvider
                vehicle.projectCode = params?.vehicle.projectCode
                vehicle.projectName = params?.vehicle.projectName
                vehicle.purpose = params?.vehicle.purpose
                vehicle.purchaseSite = params?.vehicle.purchaseSite
                vehicle.importOddNumber = params?.vehicle.importOddNumber
            }
            else
            {
                vehicle = new Vehicle(params?.vehicle)
            }

            params.vehicle.opportunity = opportunity
            if (vehicle.validate())
            {
                vehicle.save flush: true
            }
            else
            {
                println vehicle.errors
            }
            //**********************************
            def numberOfAccount1 = params?.bankAccount1?.numberOfAccount
            if (numberOfAccount1)
            {
                def bankAccount1 = new BankAccount(params?.bankAccount1)
                if (bankAccount1.validate())
                {
                    bankAccount1.save flush: true

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount1
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount1.errors
                }
            }
            if (params?.bankAccount?.id)
            {
                def bankAccount3 = BankAccount.findById(params?.bankAccount?.id)
                bankAccount3.type = BankAccountType.findById(params?.bankAccount?.type)
                bankAccount3.numberOfAccount = params?.bankAccount?.numberOfAccount
                bankAccount3.isIssuingCardImmediately = params?.bankAccount?.isIssuingCardImmediately
                bankAccount3.postAddressType = params?.bankAccount?.postAddressType
                bankAccount3.postAddress = params?.bankAccount?.postAddress
                bankAccount3.billSentMethod = params?.bankAccount?.billSentMethod
                bankAccount3.houseProperty = params?.bankAccount?.houseProperty
                bankAccount3.province = Province.findById(params?.bankAccount?.province)
                bankAccount3.type = ContactIdentityType.findById(params?.bankAccount?.type)
                bankAccount3.priority = params?.bankAccount?.priority
                bankAccount3.creditCardPaymentAccount = params?.bankAccount?.creditCardPaymentAccount
                bankAccount3.name = params?.bankAccount?.name
                bankAccount3.code = params?.bankAccount?.code
                bankAccount3.billSentEmail = params?.bankAccount?.billSentEmail
                //                bankAccount3.principalPaymentMethod=PrincipalPaymentMethod.findById(params?.bankAccount?.PrincipalPaymentMethod)
                bankAccount3.connectmanIsClientManager = params?.bankAccount?.connectmanIsClientManager
                bankAccount3.creditCardPaymentMethod = params?.bankAccount?.creditCardPaymentMethod
                bankAccount3.circulationQuota = params?.bankAccount?.circulationQuota
                bankAccount3.branchCode = params?.bankAccount?.branchCode
                bankAccount3.marketerCode = params?.bankAccount?.marketerCode
                bankAccount3.noAnnualFeeType = params?.bankAccount?.noAnnualFeeType
                bankAccount3.subType = BankAccountSubType.findById(params?.bankAccount?.subType)
                bankAccount3.wannaToIncreaseQuota = params?.bankAccount?.wannaToIncreaseQuota
                bankAccount3.creditCardPaymentType = params?.bankAccount?.creditCardPaymentType
                bankAccount3.creditCardPayMethod = params?.bankAccount?.creditCardPayMethod
                bankAccount3.surnameOfMother = params?.bankAccount?.surnameOfMother
                if (bankAccount3.validate())
                {
                    bankAccount3.save flush: true
                }
                else
                {
                    println bankAccount3.errors
                }

            }
            else
            {
                def bankAccount = new BankAccount(params?.bankAccount)
                if (bankAccount)
                {
                    if (bankAccount.validate())
                    {
                        bankAccount.save flush: true
                    }
                    else
                    {
                        println bankAccount.errors
                    }

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount?.errors
                }
            }

            def commissionRateTemp = params?.commissionRateTemp
            if (commissionRateTemp)
            {
                opportunity.commissionRate = commissionRateTemp?.toDouble() / 100
            }

        }
        else if (opportunity?.product?.name == '客群分期')
        {
            def numberOfAccount1 = params?.bankAccount1?.numberOfAccount
            if (numberOfAccount1)
            {
                def bankAccount1 = new BankAccount(params?.bankAccount1)
                if (bankAccount1.validate())
                {
                    bankAccount1.save flush: true

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount1
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount1.errors
                }
            }

            if (params?.bankAccount?.id)
            {
                def bankAccount3 = BankAccount.findById(params?.bankAccount?.id)
                bankAccount3.type = BankAccountType.findById(params?.bankAccount?.type)
                bankAccount3.numberOfAccount = params?.bankAccount?.numberOfAccount
                bankAccount3.isIssuingCardImmediately = params?.bankAccount?.isIssuingCardImmediately
                bankAccount3.postAddressType = params?.bankAccount?.postAddressType
                bankAccount3.postAddress = params?.bankAccount?.postAddress
                bankAccount3.billSentMethod = params?.bankAccount?.billSentMethod
                bankAccount3.houseProperty = params?.bankAccount?.houseProperty
                bankAccount3.province = Province.findById(params?.bankAccount?.province)
                bankAccount3.type = ContactIdentityType.findById(params?.bankAccount?.type)
                bankAccount3.priority = params?.bankAccount?.priority
                bankAccount3.creditCardPaymentAccount = params?.bankAccount?.creditCardPaymentAccount
                bankAccount3.name = params?.bankAccount?.name
                bankAccount3.code = params?.bankAccount?.code
                bankAccount3.billSentEmail = params?.bankAccount?.billSentEmail
                //                bankAccount3.principalPaymentMethod=PrincipalPaymentMethod.findById(params?.bankAccount?.PrincipalPaymentMethod)
                bankAccount3.connectmanIsClientManager = params?.bankAccount?.connectmanIsClientManager
                bankAccount3.creditCardPaymentMethod = params?.bankAccount?.creditCardPaymentMethod
                bankAccount3.circulationQuota = params?.bankAccount?.circulationQuota
                bankAccount3.branchCode = params?.bankAccount?.branchCode
                bankAccount3.marketerCode = params?.bankAccount?.marketerCode
                bankAccount3.noAnnualFeeType = params?.bankAccount?.noAnnualFeeType
                bankAccount3.subType = BankAccountSubType.findById(params?.bankAccount?.subType)
                bankAccount3.wannaToIncreaseQuota = params?.bankAccount?.wannaToIncreaseQuota
                bankAccount3.creditCardPaymentType = params?.bankAccount?.creditCardPaymentType
                bankAccount3.creditCardPayMethod = params?.bankAccount?.creditCardPayMethod
                bankAccount3.surnameOfMother = params?.bankAccount?.surnameOfMother
                if (bankAccount3.validate())
                {
                    bankAccount3.save flush: true
                }
                else
                {
                    println bankAccount3.errors
                }

            }
            else
            {
                def bankAccount = new BankAccount(params?.bankAccount)
                if (bankAccount)
                {
                    if (bankAccount.validate())
                    {
                        bankAccount.save flush: true
                    }
                    else
                    {
                        println bankAccount.errors
                    }

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount?.errors
                }
            }

            def numberOfAccount2 = params?.bankAccount2?.numberOfAccount
            if (numberOfAccount2)
            {
                def bankAccount2 = new BankAccount(params?.bankAccount2)
                if (bankAccount2.validate())
                {
                    bankAccount2.save flush: true
                }
                else
                {
                    println bankAccount2.errors
                }

                def contatBankAccount = new ContactBankAccount()
                contatBankAccount.contact = opportunity?.contact
                contatBankAccount.bankAccount = bankAccount2
                contatBankAccount.save flush: true
            }

            def commissionRateTemp = params?.commissionRateTemp
            if (commissionRateTemp)
            {
                opportunity.commissionRate = commissionRateTemp?.toDouble() / 100
            }
        }
        else if (opportunity?.product?.name == '车位分期')
        {
            def numberOfAccount1 = params?.bankAccount1?.numberOfAccount
            if (numberOfAccount1)
            {
                def bankAccount1 = new BankAccount(params?.bankAccount1)
                if (bankAccount1.validate())
                {
                    bankAccount1.save flush: true

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount1
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount1.errors
                }
            }

            if (params?.bankAccount?.id)
            {
                def bankAccount3 = BankAccount.findById(params?.bankAccount?.id)
                bankAccount3.type = BankAccountType.findById(params?.bankAccount?.type)
                bankAccount3.numberOfAccount = params?.bankAccount?.numberOfAccount
                bankAccount3.isIssuingCardImmediately = params?.bankAccount?.isIssuingCardImmediately
                bankAccount3.postAddressType = params?.bankAccount?.postAddressType
                bankAccount3.postAddress = params?.bankAccount?.postAddress
                bankAccount3.billSentMethod = params?.bankAccount?.billSentMethod
                bankAccount3.houseProperty = params?.bankAccount?.houseProperty
                bankAccount3.province = Province.findById(params?.bankAccount?.province)
                bankAccount3.type = ContactIdentityType.findById(params?.bankAccount?.type)
                bankAccount3.priority = params?.bankAccount?.priority
                bankAccount3.creditCardPaymentAccount = params?.bankAccount?.creditCardPaymentAccount
                bankAccount3.name = params?.bankAccount?.name
                bankAccount3.code = params?.bankAccount?.code
                bankAccount3.billSentEmail = params?.bankAccount?.billSentEmail
                //                bankAccount3.principalPaymentMethod=PrincipalPaymentMethod.findById(params?.bankAccount?.PrincipalPaymentMethod)
                bankAccount3.connectmanIsClientManager = params?.bankAccount?.connectmanIsClientManager
                bankAccount3.creditCardPaymentMethod = params?.bankAccount?.creditCardPaymentMethod
                bankAccount3.circulationQuota = params?.bankAccount?.circulationQuota
                bankAccount3.branchCode = params?.bankAccount?.branchCode
                bankAccount3.marketerCode = params?.bankAccount?.marketerCode
                bankAccount3.noAnnualFeeType = params?.bankAccount?.noAnnualFeeType
                bankAccount3.subType = BankAccountSubType.findById(params?.bankAccount?.subType)
                bankAccount3.wannaToIncreaseQuota = params?.bankAccount?.wannaToIncreaseQuota
                bankAccount3.creditCardPaymentType = params?.bankAccount?.creditCardPaymentType
                bankAccount3.creditCardPayMethod = params?.bankAccount?.creditCardPayMethod
                bankAccount3.surnameOfMother = params?.bankAccount?.surnameOfMother
                if (bankAccount3.validate())
                {
                    bankAccount3.save flush: true
                }
                else
                {
                    println bankAccount3.errors
                }

            }
            else
            {
                def bankAccount = new BankAccount(params?.bankAccount)
                if (bankAccount)
                {
                    if (bankAccount.validate())
                    {
                        bankAccount.save flush: true
                    }
                    else
                    {
                        println bankAccount.errors
                    }

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount?.errors
                }
            }

            def commissionRateTemp = params?.commissionRateTemp
            if (commissionRateTemp)
            {
                opportunity.commissionRate = commissionRateTemp?.toDouble() / 100
            }
        }
        else if (opportunity?.product?.name == '家装分期')
        {
            if (params?.House?.id)
            {
                def house = House.findById(params?.House?.id)
                house.decorationUnitprice = params?.house?.decorationUnitprice
                house.decorationArea = params?.house?.decorationArea
                house.decorationDownPaymentAmount = params?.house?.decorationDownPaymentAmount
                house.decorationTotalPrice = params?.house?.decorationTotalPrice
                house.decorationMethod = params?.house?.decorationMethod
                house.decorationCompany = params?.house?.decorationCompany
                house.houseProperty = params?.house?.houseProperty
                house.houseSubType = params?.house?.houseSubType
                house.purchaseArea = params?.house?.purchaseArea
                house.purchaseAmount = params?.house?.purchaseAmount
                house.address = params?.house?.address
                house.status = params?.house?.status
                house.decorationType = params?.house?.decorationType
                house.projectName = params?.house?.projectName
                if (params?.purchaseDate)
                {
                    house.purchaseDate = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.purchaseDate)
                }
                if (params?.decorationContractTime)
                {
                    house.decorationContractTime = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.decorationContractTime)
                }
                if (params?.decorationTime)
                {
                    house.decorationTime = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.decorationTime)
                }
                if (params?.houseDeliveryDate)
                {
                    house.houseDeliveryDate = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.houseDeliveryDate)
                }
                if (house.validate())
                {
                    house.save flush: true
                }
                else
                {
                    println house?.errors
                }
            }
            else
            {
                def house = new House(params?.house)
                house.opportunity = opportunity
                if (params?.purchaseDate)
                {
                    house.purchaseDate = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.purchaseDate)
                }
                if (params?.decorationContractTime)
                {
                    house.decorationContractTime = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.decorationContractTime)
                }
                if (params?.decorationTime)
                {
                    house.decorationTime = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.decorationTime)
                }
                if (params?.houseDeliveryDate)
                {
                    house.houseDeliveryDate = new SimpleDateFormat("yyyy-MM-dd").parse(params?.house?.houseDeliveryDate)
                }
                if (house.validate())
                {
                    house.save flush: true
                }
                else
                {
                    println house?.errors
                }
            }

            def numberOfAccount1 = params?.bankAccount1?.numberOfAccount
            if (numberOfAccount1)
            {
                def bankAccount1 = new BankAccount(params?.bankAccount1)
                if (bankAccount1.validate())
                {
                    bankAccount1.save flush: true

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount1
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount1.errors
                }
            }

            if (params?.bankAccount?.id)
            {
                def bankAccount3 = BankAccount.findById(params?.bankAccount?.id)
                bankAccount3.type = BankAccountType.findById(params?.bankAccount?.type)
                bankAccount3.numberOfAccount = params?.bankAccount?.numberOfAccount
                bankAccount3.isIssuingCardImmediately = params?.bankAccount?.isIssuingCardImmediately
                bankAccount3.postAddressType = params?.bankAccount?.postAddressType
                bankAccount3.postAddress = params?.bankAccount?.postAddress
                bankAccount3.billSentMethod = params?.bankAccount?.billSentMethod
                bankAccount3.houseProperty = params?.bankAccount?.houseProperty
                bankAccount3.province = Province.findById(params?.bankAccount?.province)
                bankAccount3.type = ContactIdentityType.findById(params?.bankAccount?.type)
                bankAccount3.priority = params?.bankAccount?.priority
                bankAccount3.creditCardPaymentAccount = params?.bankAccount?.creditCardPaymentAccount
                bankAccount3.name = params?.bankAccount?.name
                bankAccount3.code = params?.bankAccount?.code
                bankAccount3.billSentEmail = params?.bankAccount?.billSentEmail
                //                bankAccount3.principalPaymentMethod=PrincipalPaymentMethod.findById(params?.bankAccount?.PrincipalPaymentMethod)
                bankAccount3.connectmanIsClientManager = params?.bankAccount?.connectmanIsClientManager
                bankAccount3.creditCardPaymentMethod = params?.bankAccount?.creditCardPaymentMethod
                bankAccount3.circulationQuota = params?.bankAccount?.circulationQuota
                bankAccount3.branchCode = params?.bankAccount?.branchCode
                bankAccount3.marketerCode = params?.bankAccount?.marketerCode
                bankAccount3.noAnnualFeeType = params?.bankAccount?.noAnnualFeeType
                bankAccount3.subType = BankAccountSubType.findById(params?.bankAccount?.subType)
                bankAccount3.wannaToIncreaseQuota = params?.bankAccount?.wannaToIncreaseQuota
                bankAccount3.creditCardPaymentType = params?.bankAccount?.creditCardPaymentType
                bankAccount3.creditCardPayMethod = params?.bankAccount?.creditCardPayMethod
                bankAccount3.surnameOfMother = params?.bankAccount?.surnameOfMother
                if (bankAccount3.validate())
                {
                    bankAccount3.save flush: true
                }
                else
                {
                    println bankAccount3.errors
                }

            }
            else
            {
                def bankAccount = new BankAccount(params?.bankAccount)
                if (bankAccount)
                {
                    if (bankAccount.validate())
                    {
                        bankAccount.save flush: true
                    }
                    else
                    {
                        println bankAccount.errors
                    }

                    def contatBankAccount = new ContactBankAccount()
                    contatBankAccount.contact = opportunity?.contact
                    contatBankAccount.bankAccount = bankAccount
                    contatBankAccount.save flush: true
                }
                else
                {
                    println bankAccount?.errors
                }
            }

            // 厂商贴息费率
            def commissionRateTemp = params?.commissionRateTemp
            if (commissionRateTemp)
            {
                opportunity.commissionRate = commissionRateTemp?.toDouble() / 100
            }
            // 客户费率
            def monthlyInterestTemp = params?.monthlyInterestTemp
            if (monthlyInterestTemp)
            {
                opportunity.monthlyInterest = monthlyInterestTemp?.toDouble() / 100
            }
            opportunity.save flush: true
        }
        if (opportunity.validate())
        {
            opportunity.save flush: true
        }
        else
        {
            println opportunity.errors
        }
        render([code: 200] as JSON)

    }

    @Transactional
    @Secured('permitAll')
    def opportunitySave(Opportunity opportunity)
    {
        // 保存借款人信息 并更新opportunity的借款人信息
        def contact = opportunity.contact
        //        contact.birthday=new SimpleDateFormat("yyyy年MM月dd日").parse(params?.contact?.birthday)
        if (contact.validate())
        {
            contact.save(flush: true)
        }
        else
        {
            println contact.errors
        }
        opportunity.fullName = params?.contact?.fullName
        opportunity.cellphone = params?.contact?.cellphone
        opportunity.idNumber = params?.contact?.idNumber
        opportunity.maritalStatus = params?.contact?.maritalStatus
        //联系人信息
        if (params?.linkContact0?.id)
        {
            def contact1 = Contact.findById(params?.linkContact0?.id)
            def opportunityContact = OpportunityContact.findById(params?.linkContact0?.opportunityContact?.id)
            contact1.fullName = params?.linkContact0?.fullName
            opportunityContact.connectedType = OpportunityContactType.findById(params?.linkContact0?.connectedType)
            contact1.companyName = params?.linkContact0?.companyName
            contact1.cellphone = params?.linkContact0?.cellphone
            if (contact1.validate())
            {
                contact1.save(flush: true)
            }
            else
            {
                println contact1.errors
            }
            if (opportunityContact.validate())
            {
                opportunityContact.save(flush: true)
            }
            else
            {
                println opportunityContact.errors
            }

        }
        if (params?.linkContact1?.id)
        {
            def contact1 = Contact.findById(params?.linkContact1?.id)
            def opportunityContact = OpportunityContact.findById(params?.linkContact1?.opportunityContact?.id)
            contact1.fullName = params?.linkContact1?.fullName
            opportunityContact.connectedType = OpportunityContactType.findById(params?.linkContact1?.connectedType)
            contact1.companyName = params?.linkContact1?.companyName
            contact1.cellphone = params?.linkContact1?.cellphone
            if (contact1.validate())
            {
                contact1.save(flush: true)
            }
            else
            {
                println contact1.errors
            }
            if (opportunityContact.validate())
            {
                opportunityContact.save(flush: true)
            }
            else
            {
                println opportunityContact.errors
            }

        }

        if (opportunity.validate())
        {
            opportunity.save flush: true

        }
        else
        {
            println opportunity.errors
        }

        //调百融接口返回结果页面
        def result1 = componentService.evaluate(Component.findByName("百融进件规则"), opportunity)
        println "百融进件规则" + result1
        // def opportunityFlexFieldCategory1 = OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, FlexFieldCategory.findByName("百融进件规则"))

        def result2 = componentService.evaluate(Component.findByName("百融额度测算"), opportunity)
        println "百融额度测算" + result2
        //   def opportunityFlexFieldCategory2 = OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, FlexFieldCategory.findByName("额度测算结果"))
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)

        respond opportunity, model: [opportunityFlexFieldCategorys: opportunityFlexFieldCategorys], view: "form5"
    }

    @Secured('permitAll')
    @Transactional
    def successfulListSave(Opportunity opportunity)
    {
        def fieldId = params?.fieldId

        if (fieldId)
        {
            def opportunityFlexField = OpportunityFlexField.findById(fieldId)
            //            def opportunityFlexField = OpportunityFlexField.findByNameAndCategory(name, OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, FlexFieldCategory.findByName("额度测算结果")))
            if (opportunityFlexField)
            {
                opportunity.maximumAmountOfCredit = Double.parseDouble(opportunityFlexField?.value ? opportunityFlexField?.value : "0")
                opportunity.ompositeMonthlyInterest = Double.parseDouble(opportunityFlexField?.defaultValue ? opportunityFlexField?.defaultValue : "0")
                opportunity.commission = opportunity.maximumAmountOfCredit * opportunity.monthlyInterest
                if (opportunity.validate())
                {
                    opportunity.save flush: true

                }
                else
                {
                    println opportunity.errors
                }
                render("保存成功")
            }
            else
            {
                println("选择的产品没保存？")
                render("选择的产品没保存？")
            }
        }
        else
        {
            render("提交选择失败")
        }
    }

    /***********************************test******************************************************/
    //视频面签web页登录
    @Secured('permitAll')
    def login1()
    {
    }

    @Secured(['isAuthenticated()'])
    //视频面签web页
    def remoteSignface1()
    {

    }

    //订单信息修改页
    @Secured('permitAll')
    def editOpportunity1()
    {
        def opportunity = Opportunity.find("from Opportunity o where lower(o.serialNumber) = lower(${params?.serialNumber})")

        //问卷
        //        questionnaireInstanceService.initQuestionnaireInstance(opportunity)
        //
        //        def questionnaireInstance = QuestionnaireInstance.findByTypeAndOpportunity(QuestionnaireType.findByName(opportunity?.product?.name), opportunity)
        //todo 风险决策结果
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)
        //todo 预警信息

        respond opportunity, model: [opportunity: opportunity, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys]
    }
}
